<template>
	<view class="content">
		<view class="app-title ac">
			<view class="fl" @click="back">
				<image class="back" src="/static/img/back.png"></image>
			</view>
			<text @click="addressTest()">创建问题单</text>
		</view>
		<view class="top-bg"></view>


		<view class="detail">
			<u-cell-group>
				<u-cell-item title="接报时间:"  v-if="!appServerStr.includes('接报时间')" :value="
            data_list.receiveTime == '' ? '请选择' : data_list.receiveTime
          " @click="
            show_date = true;
            date_type = 'receiveTime';
          ">
				</u-cell-item>
				<u-cell-item title="问题开始时间:" v-if="!appServerStr.includes('问题开始时间')" :value="
            data_list.faultStartTime == '' ? '请选择' : data_list.faultStartTime
          " @click="
            show_date = true;
            date_type = 'faultStartTime';
          ">
				</u-cell-item>
				<u-radio-group v-model="data_listFaultstatus" style="height: 50px; width: 100%" placement="row" v-if="!appServerStr.includes('问题位置')">
					<text style="display: inline-block; line-height: 50px; margin-right: 20%">问题位置:</text>
					<u-radio :name="1" :disabled="false">车站</u-radio>
					<u-radio :name="2" :disabled="false">区间</u-radio>
					<u-radio :name="3" :disabled="false">列车</u-radio>
				</u-radio-group>
				<hr />
				<u-cell-item title="线路" :value="lineName == '' ? '请选择' : lineName"  v-if="!appServerStr.includes('线路')" @click="
            show_picker = true;
            columns = lineTree;
            label_name = 'name';
            value_name = 'idK';
          "></u-cell-item>

				<u-cell-item title="问题地点"  v-if="!appServerStr.includes('问题地点')" :value="stationName == '' ? '请选择' : stationName" @click="
			filterStation();
            show_station = true;
            label_name = 'name';
            value_name = 'id';
          "></u-cell-item>

				<u-cell-item title="填  写 人:" :value="username" :arrow="false" v-if="!appServerStr.includes('填写人')"></u-cell-item>
				<!-- <u-field v-model="data_list.discoverer" label="发  现 人:" placeholder="请填写"></u-field> -->
				<u-cell-item title="发  现 人:" :value="data_list.discoverer"  v-if="!appServerStr.includes('发现人')" @click="show_people = true;
            columns = leaderOptions;
            label_name = 'name';
			selece_type='people'
            value_name = 'idK';">

				</u-cell-item>
				<u-field v-model="data_list.contactPhone" label="发现人联系电话:" placeholder="请填写" v-if="!appServerStr.includes('发现人联系电话')"></u-field>
			</u-cell-group>

			<u-radio-group v-model="data_listOwnerDepartment" style="height: 50px; width: 100%" placement="row"  v-if="!appServerStr.includes('是否本部门问题')">
				<text style="display: inline-block; line-height: 50px; margin-right: 34%">是否是本部门问题:</text>
				<u-radio :name="1" :disabled="false">是</u-radio>
				<u-radio :name="2" :disabled="false">否</u-radio>
			</u-radio-group>
			<hr />

			<u-cell-item title="设备类型:" v-if="!appServerStr.includes('设备类型')" :value="!data_list.equTypeName ? '请选择' : data_list.equTypeName"
				@click="getEquTypeByStationId() ">
			</u-cell-item>

			<u-cell-item title="设备:" v-if="!appServerStr.includes('设备')" :value="data_list.equName?data_list.equName:'请选择'"
				@click.self="show_device = true;  getEquList();deviceName=data_list.equName">
			</u-cell-item>
			<u-cell-item title="问题现象" v-if="!appServerStr.includes('问题现象')" :value="data_list.faultItem == '' ? '请选择' : data_list.faultItem" 
			  @click="checkReson" ></u-cell-item>
			<view class="job-detail"><text>问题现象概述：</text> </view>
			<textarea class="text" v-model="data_list.faultIssue"></textarea>
			<view class="job-detail">备注及其它：</view>
			<textarea class="text" v-model="data_list.remark"></textarea>
			<view class="btn">
				<button style="margin-right: 34rpx" class="cancel-btn fl" @click="back">
					取消
				</button>
				<button class="default-btn" @click="pushData(1)">保存</button>
				<button class="default-btn fr" @click="pushData(2)">提交</button>
			</view>
		</view>

		<view class="full" v-show="show_picker || show_date || show_station"></view>
		<u-picker v-model="show_date" mode="time" :params="params" @confirm="setDate" @cancel="onCancel"></u-picker>
		<u-select v-model="show_picker" :list="columns" :label-name="label_name" :value-name="value_name"
			@confirm="onConfirm" @cancel="onCancel">
		</u-select>
		<selectDevice v-show="show_device" :deviceName="deviceName" :device="optionEquName" @close="show_device = false"
			@setDevice="setDevice"></selectDevice>
		<SelectStation v-show="show_station" :faultStatus="data_listFaultstatus" :station="station_options"
			@close="show_station = false" @setStation="setStation"></SelectStation>
		<PeopleSelect v-if="show_people" :people="leaderOptions" :peopleName="data_list.discoverer"
			@setPeople="setPeople" :faultStatus='1' @close="show_people=false"> </PeopleSelect>
	</view>
</template>

<script>
	import {
		PMS_DICT_CONTROLLER,
		WORK_CONTROLLER
	} from "../../api/pms";
	import {
		EQUCONTROLLER
	} from '../../api/eqt.js'
	import SelectStation from "../../components/faultClosedLoop/selectStation";
	import selectDevice from '../../components/myWork/viewWork/selectDevice.vue'
	import PeopleSelect from "../../components/faultClosedLoop/peopleSelect.vue"
	import {
		mapState
	} from "vuex";

	export default {
		components: {
			SelectStation,
			selectDevice,
			PeopleSelect
		},
		computed: {
			...mapState([
				"workOrderType",
				"workProfession",
				"workOrderState",
				"lineTree",
				"reeByOrgnum",
				"userInfo",
				"fault",
				"appServer",
			]),
			appServerStr(){
				return this.appServer?.faultUnshow || "";
			},
		},
		watch: {
			data_listFaultstatus(newValue, oldValue) {
				console.log('newValue', newValue)
				this.lineName = "";
				this.stationName = "";
				this.station_options = [];
			},
		},
		data() {
			return {
				label_name: "",
				value_name: "",
				username: uni.getStorageSync("username") || "",
				lineName: "",
				stationName: "",
				station_options: [],
				params: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true,
				},
				columns: [],
				data_listFaultstatus: "",
				data_listOwnerDepartment: "",
				data_list: {
					contactPhone: "",
					discoverer: "",
					faultIssue: "",
					faultLocation: [],
					faultStartTime: "",
					faultstatus: "",
					lineId: "",
					ownerDepartment: "",
					receiveTime: "",
					remark: "",
					subType: "",
					equName: "",
					equID: "",
					equtype: "",
					equTypeName: ""
				},
				date_type: true,
				show_picker: false,
				show_date: false,
				show_station: false,
				show_device: false,
				show_people: false,
				deviceName: "",
				optionEqu: [],
				optionEquName: [],
				stationGroup: [],
				leaderOptions: []
			};
		},
		created() {
			this.lineTree.map((item) => {
				item.extra = {
					type: "line",
				};
			});
			// console.log(this.lineTree);
			this.setReceiveTime();
			this.getNameByOrgId()
		},
		onBackPress() {
			uni.switchTab({
				url: "/pages/index/index",
			});
		},
		methods: {
			async checkReson(){
				this.columns = this.fault
				this.selece_type ="reason"
				this.label_name='value'
				this.value_name = "code"
				this.show_picker = true
				
			},
			setPeople(obj) {
				this.data_list.discoverer = obj.name.toString();
				// this.listOrderData.constructPerson = obj.id.toString();
				let leaderId = obj.id.toString()
				let filterPeople = this.leaderOptions.filter(item => item.idK == leaderId)
				this.data_list.contactPhone = filterPeople[0]?.phone
				this.show_people = false;
			},
			getNameByOrgId() {
				this.fetch(
					"get",
					this.$store.state.baseUrl + WORK_CONTROLLER.GET_NAME_BY_ORGID, {
						num: ''
					}
				).then((res) => {
					if (res?.success) {
						this.leaderOptions = res?.data;
					}
				});

			},
			filterStation() {
				if (this.data_listFaultstatus == 1) {
					this.stationGroup.forEach(item => {
						let type = item.type.split('-')
						if (type[1] == '车站') {
							this.station_options = item.station
						}
					})
				}
				if (this.data_listFaultstatus == 2) {
					this.stationGroup.forEach(item => {
						let type = item.type.split('-')
						if (type[1] == '区间') {
							this.station_options = item.station
						}
					})
				}
			},
			setDevice(obj) {
				this.data_list.equName = obj.name.toString();
				this.data_list.equId = obj.id.toString();
				this.show_device = false;
			},
			getEquTypeByStationId(param) {
				if (this.data_list.faultLocation.length == 0){
					 uni.showToast({
						title: "请先选择问题地点~",
						icon: "none",
					});
					return
				}
				this.columns = []
				this.fetch(
					"GET",
					this.$store.state.baseUrl + EQUCONTROLLER.GET_EQU_TYPE_BY_STATIONID, {
						stationId: this.data_list.faultLocation.toString(),
					}, false
				).then((res) => {
					if (res.returnCode == 2004) {
						this.selece_type = 'equTypeName'
						this.label_name = 'name'
						this.value_name = 'idk'
						this.columns = res?.data
						console.log('this.columns', this.columns)
						this.show_picker = true
					}
				})
			},
			/**
			 * 根据选择的设备类型获取 设备列表 
			 */
			async getEquList() {
				this.fetch(
					"post",
					this.$store.state.baseUrl + WORK_CONTROLLER.POST_EQU_EQULIST, {
						equtype: this.data_list.equTypeId,
						stationId: this.data_list.faultLocation.toString(),
						page: 1,
						size: 9999999,
					}, false
				).then((res) => {
					if (res?.data) {
						this.optionEquName = res?.data?.content;
						this.optionEquName = this.reduceArray(this.optionEquName, "idk");
					}
				})
			},
			// 数组对象元素去重
			reduceArray(initialArr, attr) {
				// const uniqueArr = Array.from(new Set(arr.map(JSON.stringify)), JSON.parse);
				let uniqueArr = initialArr.reduce((acc, obj) => {
					let existingObj = acc.find((item) => item[attr] === obj[attr]);
					if (!existingObj) {
						acc.push(obj);
					}
					return acc;
				}, []);
				return uniqueArr;
			},
			radioGroupFaultStatusChange(e) {
				// console.log(e);
			},
			addressTest() {
				uni.showToast({
					title: this.$store.state.baseFaultUrl,
					icon: "none",
				});
			},
			back() {
				uni.navigateTo({
					url: "/pages/index/index",
				});
			},
			setReceiveTime() {
				let now = new Date();
				let str =
					now.getFullYear() +
					"-" +
					(now.getMonth() + 1 < 10 ?
						"0" + (now.getMonth() + 1) :
						now.getMonth() + 1) +
					"-" +
					(now.getDate() < 10 ? "0" + now.getDate() : now.getDate()) +
					" " +
					(now.getHours() < 10 ? "0" + now.getHours() : now.getHours()) +
					":" +
					(now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes()) +
					":" +
					(now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds());
				this.data_list.receiveTime = str;
			},
			onConfirm(item) {
				console.log('item--', item)
				if (item[0]?.extra?.type == "line") {
					this.lineName = item[0].label;
					this.data_list.lineId = item[0].value;
					this.stationName = "";
					if (this.data_listFaultstatus == 1 || this.data_listFaultstatus == 2) {
						this.getStationOption(item);
					} else if (this.data_listFaultstatus == 3) {
						this.getTrain(item);
					}
					return
				}
				if (this.selece_type == 'equTypeName') {
					this.data_list.equTypeName = item[0].label
					this.data_list.equTypeId = item[0].value
					this.getEquList()
				}
				if (this.selece_type == 'people') {
					this.data_list.discoverer = item[0].label
					let leaderId = item[0].value
					let filterPeople = this.leaderOptions.filter(item => item.idK == leaderId)
					this.data_list.contactPhone = filterPeople[0]?.phone
				}
				if(this.selece_type =='reason'){
					this.data_list.faultProblem =item[0].label
					this.data_list.faultItem =  item[0].label
				}
				// else if (item[0].extra.type == "station") {

				//   // this.stationName = item[0].label;
				//   // this.data_list.faultLocation = [item[0].value];
				// }
				this.onCancel();
			},
			onCancel() {
				this.show_picker = false;
				this.show_date = false;
				this.show_station = false;
			},
			setDate(obj) {
				let str =
					obj.year +
					"-" +
					obj.month +
					"-" +
					obj.day +
					" " +
					obj.hour +
					":" +
					obj.minute +
					":" +
					obj.second;
				switch (this.date_type) {
					case "receiveTime":
						this.data_list.receiveTime = str;
						break;
					case "faultStartTime":
						this.data_list.faultStartTime = str;
						break;
					default:
				}
				this.onCancel();
			},
			getTrain(obj) {
				this.fetch(
					"get",
					this.$store.state.baseUrl + "/pmsDict/train/getNameByLineId", {
						lineId: obj[0].value
					}
				).then((res) => {
					if (res?.success) {
						this.station_options = res?.data.map((item) => {
							item.extra = {
								type: "station",
								checked: false,
								id: item.id,
							};
							return item;
						});
					} else {
						this.station_options = [];
					}
				});
			},
			getStationOption(obj) {
				this.fetch(
					"GET",
					this.$store.state.baseFaultUrl + "/kunmingdict/station/nameGroupType", {
						lineIds: this.data_list.lineId,
					},
					false,
					this.$store.state.faultCLHeader
				).then((res) => {
					if (res.success) {
						console.log('res---', res)
						let temp = [];
						let copyTemp = []
						res.data.forEach((item) => {
							temp = temp.concat(item.childs);
						});
						copyTemp = res.data.map(item => {
							let child = item.childs.map(chilItem => {
								return {
									...chilItem,
									extra: {
										type: "station",
										checked: false,
										id: chilItem.id,
									}
								}
							})
							return {
								type: item.type,
								station: child
							}
						})
						// this.station_options = res.data[0].childs || []; //暂时特殊处理
						temp.map((item) => {
							item.extra = {
								type: "station",
								checked: false,
								id: item.id,
							};
							item.text = item.name;
						});
						this.stationGroup = copyTemp
						this.station_options = temp;
						console.log('this.station_options', this.station_options, copyTemp)
					}
				});
			},
			setStation(obj) {
				this.stationName = obj.name.toString();
				this.data_list.faultLocation = obj.id;
				this.show_station = false;
			},
			pushData(submitType) {
				if (this.checkInputNull() != "success") return;
				this.data_list.faultstatus =
					this.data_listFaultstatus == 1 ?
					"车站" :
					this.data_listFaultstatus == 2 ?
					"区间" :
					"列车";
				this.data_list.ownerDepartment =
					this.data_listOwnerDepartment == 1 ? "Y" : "N";
				this.data_list.subType = submitType;

				// //暂时特殊处理
				// this.data_list.ownerDepartment = 'Y';
				// if (this.data_list.faultstatus == "区间")
				//   this.data_list.faultstatus = "车站";

				if (this.data_list.contactPhone != "") {
					if (!/^1[3|4|5|7|8]\d{9}$/.test(this.data_list.contactPhone))
						return uni.showToast({
							title: "手机号码有误，请重填",
							icon: "none",
						});
				}
				if (
					new Date(this.data_list.faultStartTime).getTime() >
					new Date(this.data_list.receiveTime).getTime()
				)
					return uni.showToast({
						title: "问题开始时间不能晚于接报时间",
						icon: "none",
					});
				if (
					this.data_list.faultstatus == "区间" &&
					this.data_list.faultLocation.length != 2
				)
					return uni.showToast({
						title: "请选择两个站点~",
						icon: "none",
					});

				this.fetch(
					"POST",
					this.$store.state.baseUrl + "/fault/save",
					this.data_list,
					true,
					this.$store.state.faultCLHeader
				).then((res) => {
					if (res.success) {
						uni.showToast({
							title: "操作完成",
							icon: "none",
						});
						setTimeout(() => {
							uni.navigateTo({
								url: "/pages/index/index",
							});
						}, 800);
					} else {
						uni.showToast({
							title: res.message,
							icon: "none",
						});
					}
				});
			},
			checkInputNull() {
				if (this.data_list.receiveTime == "")
					return uni.showToast({
						title: "接报时间不能为空",
						icon: "none",
					});
				if (this.data_list.faultStartTime == "")
					return uni.showToast({
						title: "问题开始时间不能为空",
						icon: "none",
					});
				if (this.data_listFaultstatus == "")
					return uni.showToast({
						title: "问题位置不能为空",
						icon: "none",
					});
				if (this.data_list.lineId == "")
					return uni.showToast({
						title: "线路不能为空",
						icon: "none",
					});
				if (this.data_list.faultLocation.length == 0)
					return uni.showToast({
						title: "问题地点不能为空",
						icon: "none",
					});
				if (this.data_list.discoverer == "")
					return uni.showToast({
						title: "发现人不能为空",
						icon: "none",
					});
				// if (this.data_list.contactPhone == '') return uni.showToast({
				// 	title: '发现人电话不能为空',
				// 	icon: 'none'
				// });

				if (this.data_list.faultIssue == "")
					return uni.showToast({
						title: "问题现象不能为空",
						icon: "none",
					});
				if (this.data_listOwnerDepartment == "")
					return uni.showToast({
						title: "请选择是否为本部门问题",
						icon: "none",
					});
				if (
					this.data_listFaultstatus == 2 &&
					this.data_list.faultLocation.length > 2
				)
					return uni.showToast({
						title: "只能选择两个地点",
						icon: "none",
					});
				return "success";
			},
		},
	};
</script>

<style scoped>
	.content{
		font-size: 15px;
		color:""
	}
	.detail {
		height: auto;
		padding-bottom: 16px;
		margin-top: -170px;
	}

	.job-detail {
		line-height: 45px;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		padding-right: 20px;
		align-items: center;
	}

	.detail>.text {
		background: #f9fbfe;
		border: 1px solid #f1f1f1;
		border-radius: 6px;
		padding: 10px;
		font-size: 14px;
		height: 104px;
		overflow: auto;
	}

	.detail>.photo {
		overflow-x: auto;
		width: 100%;
		height: 100px;
		white-space: nowrap;
	}

	.detail>.photo>.img-item {
		width: 80px;
		height: 80px;
		margin-right: 10px;
		border-radius: 6px;
		display: inline-block;
		vertical-align: middle;
	}

	.detail>.btn {
		margin: 30rpx 26rpx 0 0;
	}

	.u-label {
		width: 75px !important;
	}

	.detail>.btn>button {
		display: inline-block;
		width: 30%;
	}

	.photo .images {
		width: 80px;
		height: 80px;
	}

	.van-cell {
		padding: 13px 16px;
	}

	.van-hairline--top-bottom::after,
	.van-hairline-unset--top-bottom::after {
		border-top: 0px;
	}

	.van-cell__value {
		color: #3e3a39;
	}

	hr {
		border: 0;
		border-top: 1px solid #F2F3F6;
	}
</style>